<template>
  <j-modal :title="title" :width="800" :visible="visible" :confirmLoading="confirmLoading" switchFullscreen @ok="handleOk"
    @cancel="handleCancel" cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">

        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="setName" label="集合名称">
          <a-input placeholder="请输入集合名称" v-model="model.setName" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryName" label="合集分类名称">
          <a-select v-model="model.categoryName" placeholder="请选择分类">
            <a-select-option :value="item.name" v-for="(item, index) in categoryList" :key="index">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="setIntroductionShort" label="合集短简介">
          <a-input placeholder="请输入合集短简介" v-model="model.setIntroductionShort" />
        </a-form-model-item>

        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="setIntroductionLong" label="合集长简介">
          <a-input placeholder="请输入它的简介吧~" v-model="model.setIntroductionLong" type="textarea" />
        </a-form-model-item>

        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="tagsValidator" label="标签">
          <template v-for="(tag, index) in tags">
            <a-tooltip v-if="tag.length > 20" :key="tag" :title="tag">
              <a-tag :key="tag" :closable="true" @close="() => handleClose(tag)">
                {{ `${tag.slice(0, 20)}...` }}
              </a-tag>
            </a-tooltip>
            <a-tag v-else :key="tag" :closable="true" @close="() => handleClose(tag)">
              {{ tag }}
            </a-tag>
          </template>
          <a-input v-if="inputVisible" ref="input" type="text" size="small" :style="{ width: '78px' }" :value="inputValue"
            @change="handleInputChange" @blur="handleInputConfirm" @keyup.enter="handleInputConfirm" />
          <a-tag v-else style="background: #fff; borderStyle: dashed;" @click="showInput">
            <a-icon type="plus" /> New Tag
          </a-tag>
        </a-form-model-item>

        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="coverLevel" label="预览图（水平）">
          <boboCropper v-model="model.coverLevel" :aspectRatio="225 / 120"></boboCropper>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="coverVertical" label="预览图（垂直）">
          <boboCropper v-model="model.coverVertical" :aspectRatio="90 / 120"></boboCropper>
        </a-form-model-item>

        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="coverVideoUrl" label="预览视频地址">
          <!-- <a-input placeholder="请输入预览视频地址" v-model="model.coverVideoUrl" /> -->
          <a-upload accept="video/*" name="file" :multiple="true" :action="uploadVideoAction" :headers="headers"
            :file-list="videoList" @change="handleCoverVideoChange">
            <a-button> <a-icon type="upload" /> Click to Upload </a-button>
          </a-upload>
        </a-form-model-item>

      </a-form-model>
    </a-spin>
  </j-modal>
</template>

<script>
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
import { httpAction, getAction } from '@/api/manage'
import moment from "moment"
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'


export default {
  name: "VideoSetDOModal",
  data() {
    return {
      title: "操作",
      headers: {},
      uploadAction: '',
      uploadVideoAction: '',
      visible: false,
      videoList: [],
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      imgLoading: false,
      confirmLoading: false,
      validatorRules: {
        setName: [
          { required: true, message: '合集名称不允许为空', trigger: 'blur' },
          { min: 3, max: 10, message: '请输入3-10个字符', trigger: 'blur' },
        ],
        categoryName: [
          { required: true, message: '合集分类不允许为空', trigger: 'blur' },
        ],
        setIntroductionShort: [
          { required: true, message: '短简介不允许为空', trigger: 'blur' },
        ],
        setIntroductionLong: [
          { required: true, message: '长简介不允许为空', trigger: 'blur' },
        ],
        tagsValidator: [
          { required: true, trigger: 'blur', validator: this.tagsValidator },
        ],
        coverLevel: [
          { required: true, trigger: 'change', validator: this.uploadCoverLevelChange },
        ],
        coverVertical: [
          { required: true, trigger: 'change', validator: this.uploadCoverVerticalChange },
        ],
        coverVideoUrl: [
          { required: true, trigger: 'change', validator: this.uploadCoverVideoChange },
        ],
      },
      categoryList: [],
      tags: [],
      inputVisible: false,
      inputValue: '',
      url: {
        add: "/admin/videoSetDO/add",
        edit: "/admin/videoSetDO/edit",
        categoryAll: "/admin/categoryDO/all",
      },
    }
  },
  created() {
    this.initCategory();
  },
  methods: {
    queryVideoSetList(value) {
      let param = {
      }
      if (value) {
        param = {
          setName: value
        }
      } else {
        param = {
          limit: 40
        }
      }

      getAction(this.url.videoSetAll, param).then((res) => {
        if (res.success) {
          this.videoSetList = res.result;
        } else {
          that.$message.warning(res.message);
        }
      })
    },
    add() {
      //初始化默认值
      this.edit({});
    },
    edit(record) {

      const token = Vue.ls.get(ACCESS_TOKEN);

      this.headers = { "X-Access-Token": token }
      this.uploadAction = window._CONFIG['domianURL'] + '/upload/file'

      this.uploadVideoAction = window._CONFIG['domianURL'] + '/upload/uploadVideoToM3U8'
      this.model = Object.assign({}, record);
      this.videoList = [];
      if (this.model.tags) {
        this.tags = this.model.tags.split(",");
      }

      if (this.model.coverVideoUrl) {
        let video = {
          status: "done",
          type: "video/mp4",
          uid: "vc-upload-1682701433890-6",
          name: this.model.coverVideoUrl,
          url: this.model.coverVideoUrl
        }
        this.videoList.push(video);
      }
      console.log(this.videoList, 'this.videoListthis.videoList')
      this.visible = true;
    },
    close() {
      this.$emit('close');
      this.visible = false;
      this.$refs.form.clearValidate();
    },
    handleChangeImgCover(info) {
      if (info.file.status === 'uploading') {
        this.imgLoading = true;
        return;
      }
      if (info.file.status === 'done') {
        this.model.cover = info.file.response.result;;
        this.imgLoading = false;
        this.$forceUpdate();
      }
    },
    beforeUploadCover(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M;
    },
    handleCoverVideoChange(info) {
      let fileList = [...info.fileList];
      // 1. Limit the number of uploaded files
      //    Only to show two recent uploaded files, and old ones will be replaced by the new
      fileList = fileList.slice(-1);

      // 2. read from response and show file link
      fileList = fileList.map(file => {
        console.log(file, "file")
        if (file.response) {
          if (file.response.code == 200) {
            file.url = file.response.result;
            this.model.coverVideoUrl = file.response.result;
          } else {
            file.status = 'error';
          }

        }
        return file;
      });
      if (fileList.length == 0) {
        this.model.coverVideoUrl = '';
      }
      this.videoList = fileList;
    },
    // 自定义预览图校验
    uploadCoverLevelChange(rule, value, callback) {
      if (!this.model.coverLevel || this.model.coverLevel == '') {
        return callback(new Error('预览图片不允许为空~'));
      } else {
        return true;
      }
    },
    // 自定义预览图校验
    uploadCoverVerticalChange(rule, value, callback) {
      if (!this.model.coverVertical || this.model.coverVertical == '') {
        return callback(new Error('预览图片不允许为空~'));
      } else {
        return true;
      }
    },
    // 自定义标签校验
    tagsValidator(rule, value, callback) {
      if (!this.tags || this.tags.length < 1) {
        return callback(new Error('标签不允许为空~'));
      } else {
        return true;
      }
    },

    // 自定义预览视频校验
    uploadCoverVideoChange(rule, value, callback) {
      if (!this.model.coverVideoUrl || this.model.coverVideoUrl == '') {
        return callback(new Error('预览视频不允许为空~'));
      } else {
        return true;
      }
    },
    initCategory() {
      getAction(this.url.categoryAll, {}).then((res) => {
        if (res.success) {
          this.categoryList = res.result;
        } else {
          that.$message.warning(res.message);
        }
      })
    },
    handleOk() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }

          this.model.tags = this.tags.join(',');
          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.close();
              that.$emit('ok');
            } else {
              that.$message.error(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        } else {
          return false;
        }
      })
    },
    handleCancel() {
      this.close()
    },
    handleClose(removedTag) {
      const tags = this.tags.filter(tag => tag !== removedTag);
      console.log(tags);
      this.tags = tags;
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(function () {
        this.$refs.input.focus();
      });
    },

    handleInputChange(e) {
      this.inputValue = e.target.value;
    },

    handleInputConfirm() {
      const inputValue = this.inputValue;
      let tags = this.tags;
      if (inputValue && tags.indexOf(inputValue) === -1) {
        tags = [...tags, inputValue];
      }
      console.log(tags);
      Object.assign(this, {
        tags,
        inputVisible: false,
        inputValue: '',
      });
    },

  }
}
</script>

<style lang="less" scoped></style>